# -*- coding: utf-8 -*-
# import os, time
#import os, sys

# import imp
# import os, sys
# import xml.etree.ElementTree as xml
# from cStringIO import StringIO
#
# try:
#     imp.find_module('PySide2')
#     from PySide2.QtWidgets import *
#     from PySide2.QtGui import *
#     from PySide2.QtCore import *
#     import pyside2uic as uic
# except :
#     from PySide.QtGui import *
#     from PySide.QtCore import *
#     import pysideuic as uic

#-*- coding: utf-8 -*-
# import os, time
# import tkinter.messagebox as tm



import json
import platform
# import random
import imp
from functools import partial
import os, sys
import xml.etree.ElementTree as xml
from cStringIO import StringIO
# cmds.loadPlugin('mtoa', qt=1)
# import mtoa.lib
try:
    import shiboken2 as sbk
except:
    import shiboken as sbk
if str(sys.executable).endswith("maya.exe"):
    import maya.cmds as cmds
    import maya.mel as mel
    import pymel.core as pm
    import mtoa.utils
    import mtoa.aovs
    import mtoa.core
else:
    import maya.cmds as cmds
    import maya.mel as mel
    import pymel.core as pm
    import mtoa.utils
    import mtoa.aovs
    import mtoa.core
try:
    imp.find_module('PySide2')
    from PySide2.QtWidgets import *
    from PySide2.QtGui import *
    from PySide2.QtCore import *
    import pyside2uic as uic
except :
    from PySide.QtGui import *
    from PySide.QtCore import *
    import pysideuic as uic


# if str(sys.executable).endswith("maya.exe"):
#     import maya.cmds as cmds
#     import mtoa.lib
#     print 'saadasdasda'
#     import maya.mel as ml
#     import maya.OpenMayaUI as mui
#     # from pymel.all import *
#
#     try:
#         imp.find_module('PySide2')
#         import shiboken2 as sbk
#     except:
#         import shiboken as sbk



def loadUiType(uiFile):

    parsed = xml.parse(uiFile)
    widget_class = parsed.find('widget').get('class')
    form_class = parsed.find('class').text
    with open(uiFile, 'r') as f:
        o = StringIO()
        frame = {}
        uic.compileUi(f, o, indent=0)
        pyc = compile(o.getvalue(), '<string>', 'exec')
        exec pyc in frame
        # Fetch the base_class and form class based on their type in the xml from designer
        form_class = frame['Ui_%s' % form_class]
        base_class = eval('%s' % widget_class)
    return form_class, base_class


class randerLayerTool(QMainWindow):

    def __init__(self, parent=None):
        super(randerLayerTool, self).__init__(parent)

        self._messagebox01 = messageBox01()
        self._messagebox02 = messageBox02()
        self._messagebox03 = messageBox03()
        self._messagebox04 = messageBox04()
        self._messageBox_about = messageBox_about()

        dir_path = os.path.dirname(__file__)
        ui_file = os.path.join(dir_path, "rendest_UI.ui")
        self.form, base = loadUiType(ui_file)
        # self.ui = Browser_PySide_QTUI.Ui_TimeTable_Browser()
        self.ui = self.form()
        try:
            1/0
            import renderLayerUI_PySide_QTUI as qtpy
            self.ui = qtpy.Ui_MainWindow()
        except:
            pass
        self.zsl_zsl = {}
        self.layerDict = {'__basic':[{'all_light_group': 1, 'merge_aovs': 1},self.zsl_zsl]}  # 层数据
        self.createGrp = {}  # 层打钩数据
        self.objAttr = [
            ['aiOpaque', 'Boolean', '(Boolean)', 1, 0, 1],
            ['primaryVisibility', 'Boolean', '(Boolean)', 1, 0, 1],
            ['castsShadows', 'Boolean', '(Boolean)', 1, 0, 1],
            ['receiveShadows', 'Boolean', '(Boolean)', 1, 0, 1],
            ['aiSubdivType', 'Inter', '(none/catclark/linear)', 1, 0, 2],
            ['aiSubdivIterations', 'Inter', '(0~10[Inter])', 1, 0, 10],
            ['aiSubdivUvSmoothing', 'Inter', '(corners/borders/linear/smooth)', 1, 0, 3],
            ['aiDispHeight', 'Float', '(Float)', 0],
            ['aiDispPadding', 'Float', '(Float)', 0],
            ['aiDispZeroValue', 'Float', '(Float)', 0],
            ['aiSssSetname', 'String', '(String)']
        ]
        self.ass_objAttr = [
            ['overrideOpaque', 'Boolean', '(Boolean)', 1, 0, 1],
            ['primaryVisibility', 'Boolean', '(Boolean)', 1, 0, 1],
            ['castsShadows', 'Boolean', '(Boolean)', 1, 0, 1],
            ['overrideReceiveShadows', 'Boolean', '(Boolean)', 1, 0, 1]
        ]
        self.default = [True, True, True, True, 0, 1, 0, 1.0, 0.0, 0.0, u'']
        self.ass_default = [False, True, True, True]


        self.ui.setupUi(self)

        self.ui.pbn1.clicked.connect(self.pbn_im)  # import
        self.ui.pbn2.clicked.connect(self.pbn_ex)  # export
        self.ui.pbn3.clicked.connect(self.pbn_creat)  # create
        self.ui.pbn4.clicked.connect(self.pbn_addL)  # add
        self.ui.pbn5.clicked.connect(self.pbn_del)  # delete
        self.ui.pbn6.clicked.connect(self.pbn_addO)  # add obj
        self.ui.pbn7.clicked.connect(self.pbn_removeO)  # remove obj
        self.ui.pbn8.clicked.connect(self.pbn_select)  # select
        self.ui.pbn9.clicked.connect(self.pbn_true)
        self.ui.pbn10.clicked.connect(self.pbn_false)
        self.ui.pbn_set.clicked.connect(self.pbn_set)
        self.ui.pbn_clear.clicked.connect(self.pbn_removeL)  # clear
        # self.ui.rbn1.clicked.connect(self.rbn_1)
        self.ui.checkBox01.stateChanged.connect(self.checkBox01_04run)
        self.ui.checkBox02.stateChanged.connect(self.checkBox01_04run)
        self.ui.checkBox03.stateChanged.connect(self.checkBox01_04run)
        self.ui.checkBox04.stateChanged.connect(self.checkBox01_04run)

        self.ui.listWidget01.clicked.connect(self.lwt_1)
        self.ui.listWidget01.itemChanged.connect(self.lwtItem_1)
        self.ui.listWidget01add.itemChanged.connect(self.lwtItemadd)
        self.ui.listWidget02.clicked.connect(self.lwt_2)
        self.ui.lineEdit01.returnPressed.connect(self.pbn_addL)
        self.ui.lineEdit02.returnPressed.connect(self.pbn_set)
        self.ui.pbn_replace.clicked.connect(self.repalce)
        self.ui.pushButton.clicked.connect(self.pbn_vis)
        self.ui.actionAbout.triggered.connect(self.actionAbout)
        ###############################################################################
        ## zsl ## super
        ###############################################################################
        self.myCreatAovDirt = {}
        self.zsl_zsl = {}
        self.time_num = 1

        self._frequentAov = [
             'N', 'P', 'Z',  'AO', 'CN', 'Deep', 'diffuse',  'specular',
             'sss', 'crypto_material', 'crypto_object', 'shadow_matte',
            'motionvector', 'coat', 'emission', 'transmission'
        ]

        self._ordinaryAov = [
            'ID', 'Pref', 'RGBA',
            'albedo', 'background', 'coat_albedo', 'coat_direct', 'coat_indirect',
            'cputime', 'diffuse_albedo', 'diffuse_direct', 'diffuse_indirect', 'direct',
            'indirect', 'opacity', 'raycount', 'shadow', 'shadow_diff', 'shadow_mask',
            'specular_albedo', 'specular_direct', 'specular_indirect', 'sss_albedo',
            'sss_direct', 'sss_indirect', 'transmission_albedo', 'transmission_direct',
            'transmission_indirect', 'volume', 'volume_albedo', 'volume_direct', 'volume_indirect',
            'volume_opacity'
        ]
        # self.all_Aov = [self._frequentAov, self._ordinaryAov]
        self._aovsWhiteList = ['diffuse', 'specular', 'sss', 'shadow_matte', 'coat', 'emission', 'transmission',
                               'coat_albedo', 'coat_direct', 'coat_indirect', 'diffuse_albedo', 'diffuse_direct',
                               'diffuse_indirect', 'direct', 'indirect', 'specular_albedo', 'specular_direct',
                               'specular_indirect', 'sss_albedo', 'transmission_albedo', 'transmission_direct',
                               'transmission_indirect', 'volume', 'volume_direct', 'volume_indirect']

        self.aovNum = {0:[0, 0], 1:[1, 0], 2:[0, 1], 3:[1, 1]}

        #创建defaultArnoldDriver节点
        mtoa.core.createOptions()


        ## zsl ##
        self.ui.zsl_pbn01.clicked.connect(self.aov_addLightList)
        # self.ui.zsl_pbn02.clicked.connect(self.add_aovs)

        self.ui.zsl_cbx03.toggled.connect(self.all_light_group)
        self.ui.zsl_cbx04.toggled.connect(self.merge_aovs)

        pm.setAttr("defaultArnoldDriver.mergeAOVs", 1)
        self.ui.zsl_cbx01.toggled.connect(self.aov_selectAovChecked) #######
        self.ui.zsl_cbx02.toggled.connect(self.aov_select_abled_Checked)

        self.getAovJosn = {}
        self.getAbledJosn = {}
        self.setFixedSize(self.width(), self.height())
        self._listAovs1 = []
        self._listlightAovs1 = []
        ###############################################################################
        ## zsl ## super
        ###############################################################################

    #########################################################################################
    #########################################################################################
    ## zsl def ##
    #########################################################################################
    #########################################################################################
    def all_light_group(self):
        if self.ui.zsl_cbx03.isChecked():
            self.layerDict['__basic'][0]['all_light_group'] = 1
        else:
            self.layerDict['__basic'][0]['all_light_group'] = 0


    def zsl_addItem(self):
        print 'zsl'
        print self.layerDict
        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            pass
        else:
            selectedList = self.ui.listWidget01.currentItem().text()
            print selectedList
            for i in range(len(self._frequentAov)):
                attr = self.layerDict[selectedList]['layerAovs'][0][i]
                self.zsl_myItem = QListWidgetItem(self.ui.zsl_lwt01)
                self.zsl_myItem.setSizeHint(QSize(100, 16))
                self.zsl_myWid_F = zsl_my_Wid(self._frequentAov[i]) ######### 实例化类 ############

                self.zsl_myWid_F._myCheckBox.setChecked(self.aovNum[attr][0]) # 第一个勾
                self.zsl_myWid_F._myCheckBox.setObjectName('frequentAov_' + self._frequentAov[i] + "_aov")
                self.zsl_myWid_F._abled_checkedbox.setChecked(self.aovNum[attr][1]) # 第二个勾
                self.ui.zsl_lwt01.setItemWidget(self.zsl_myItem, self.zsl_myWid_F)
                self.zsl_myWid_F._myCheckBox.clicked.connect(self.zsl_getReturn01)
                self.zsl_myWid_F._abled_checkedbox.clicked.connect(self.zsl_getReturn02)

            self.myGroupBox1 = QGroupBox()

            self.myBtn1 = QPushButton(U'我是分割线',self)
            self.myBtn1.setEnabled(0)
            self.myBtn1.setMaximumHeight(16)
            self.myBtnItem = QListWidgetItem(self.ui.zsl_lwt01)
            self.ui.zsl_lwt01.setItemWidget(self.myBtnItem, self.myBtn1)

            for i in range(len(self._ordinaryAov)):
                attr = self.layerDict[selectedList]['layerAovs'][1][i]
                self.zsl_myItem = QListWidgetItem(self.ui.zsl_lwt01)
                self.zsl_myItem.setSizeHint(QSize(100, 16))
                self.zsl_myWid_F = zsl_my_Wid(self._ordinaryAov[i])
                self.zsl_myWid_F._myCheckBox.setObjectName('ordinaryAov_' + self._ordinaryAov[i] + "_aov")
                self.ui.zsl_lwt01.setItemWidget(self.zsl_myItem, self.zsl_myWid_F)
                self.zsl_myWid_F._myCheckBox.setChecked(self.aovNum[attr][0])
                self.zsl_myWid_F._abled_checkedbox.setChecked(self.aovNum[attr][1])

                self.zsl_myWid_F._myCheckBox.clicked.connect(self.zsl_getReturn01)
                self.zsl_myWid_F._abled_checkedbox.clicked.connect(self.zsl_getReturn02)

    def zsl_getReturn01(self):
        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            pass
        else:
            selectedList = self.ui.listWidget01.currentItem().text()
            print selectedList
            senderx = self.sender()

            aa = senderx.objectName().replace('frequentAov_', '').replace('_aov', '').replace('ordinaryAov_', '')
            if aa in self._frequentAov:
                cc = self._frequentAov
                dd = 0
            else:
                cc = self._ordinaryAov
                dd = 1
            for i in range(len(cc)):
                if cc[i] == aa:
                    bb = self.layerDict[selectedList]['layerAovs'][dd][i]
                    if bb == 0:
                        allkey = self._allkey()
                        for x in allkey:
                            if self.layerDict[x]['layerAovs'][dd][i] == 0:
                                self.layerDict[x]['layerAovs'][dd][i] = 1
                        # self.layerDict[selectedList]['layerAovs'][dd][i] = bb + 1
                    if bb == 3:
                        self.layerDict[selectedList]['layerAovs'][dd][i] = 0
                    if bb == 1:
                        self.layerDict[selectedList]['layerAovs'][dd][i] = 0

            self.lwt_1()
            print self.layerDict


    def zsl_getReturn02(self):
        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            pass
        else:
            selectedList = self.ui.listWidget01.currentItem().text()
            senderx = self.sender()
            aa = senderx.objectName().replace('_abled', '')
            if aa in self._frequentAov:
                cc = self._frequentAov
                dd = 0
            else:
                cc = self._ordinaryAov
                dd = 1
            for i in range(len(cc)):
                if cc[i] == aa:
                    bb = self.layerDict[selectedList]['layerAovs'][dd][i]
                    if bb == 1:
                        self.layerDict[selectedList]['layerAovs'][dd][i] = 3
                    if bb == 0:
                        self.layerDict[selectedList]['layerAovs'][dd][i] = 3
                        allkey = self._allkey()
                        allkey.remove(selectedList)
                        for x in allkey:
                            if self.layerDict[x]['layerAovs'][dd][i] == 0:
                                self.layerDict[x]['layerAovs'][dd][i] = 1
                    if bb == 3:
                        self.layerDict[selectedList]['layerAovs'][dd][i] = 1
            self.lwt_1()
            print self.layerDict

    def aov_selectAovChecked(self):
        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            pass
        else:
            selectedList = self.ui.listWidget01.currentItem().text()

            if self.ui.zsl_cbx01.isChecked():
                self.aov_check01_reflesh(1, selectedList)
            else:
                self.aov_check01_reflesh(0, selectedList)

    def aov_check01_reflesh(self, check, selectedList):
        aa = self.layerDict[selectedList]['layerAovs'][0]
        allkey = self._allkey()
        for i in range(len(aa)):
            if check:
                if aa[i] == 0:
                    for x in allkey:
                        if self.layerDict[x]['layerAovs'][0][i] == 0:
                            self.layerDict[x]['layerAovs'][0][i] = 1
            else:
                if aa[i] == 1:
                    for x in allkey:
                        self.layerDict[x]['layerAovs'][0][i] = 0
                if aa[i] == 3:
                    for x in allkey:
                        self.layerDict[x]['layerAovs'][0][i] = 0
        self.lwt_1()
        print self.layerDict



    def aov_select_abled_Checked(self):
        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            pass
        else:
            selectedList = self.ui.listWidget01.currentItem().text()
            if self.ui.zsl_cbx02.isChecked():
                self.aov_check02_reflesh(1, selectedList)
            else:
                self.aov_check02_reflesh(0, selectedList)

    def aov_check02_reflesh(self, check, selectedList):
        aa = self.layerDict[selectedList]['layerAovs'][0]
        allkey = self._allkey()
        for i in range(len(aa)):
            if check:
                if aa[i] == 1:
                    for x in allkey:
                        self.layerDict[x]['layerAovs'][0][i] = 3

                if aa[i] == 0:
                    for x in allkey:
                        self.layerDict[x]['layerAovs'][0][i] = 3
            else:
                if aa[i] == 3:
                    for x in allkey:
                        if x == selectedList:
                            self.layerDict[selectedList]['layerAovs'][0][i] = 1
                        elif self.layerDict[x]['layerAovs'][0][i] == 3:
                            self.layerDict[x]['layerAovs'][0][i] = 1
        self.lwt_1()

    def merge_aovs(self):
        if self.ui.zsl_cbx04.isChecked():
            self.layerDict['__basic'][0]['merge_aovs'] = 1
        else:
            self.layerDict['__basic'][0]['merge_aovs'] = 0


    def merge_avos_run(self):
        if self.layerDict['__basic'][0]['merge_aovs']:
            pm.setAttr("defaultArnoldDriver.mergeAOVs", 1)
        else:
            pm.setAttr("defaultArnoldDriver.mergeAOVs", 0)

    def aov_addLightList(self):
        self.error_create_light = []
        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            pass
        else:
            self.ui.zsl_lwt02.clear()
            lightType = ['aiSkyDomeLight', 'aiAreaLight', 'spotLight', 'directionalLight', 'pointLight']
            myGetAllLight = pm.ls(type=lightType)
            light_in_world = []
            for x in myGetAllLight:
                if len(self.myJudge01(x)) == 0:
                    lightAovName = pm.getAttr('%s.aiAov' % x)
                    if lightAovName:
                        light_in_world.append(lightAovName)
                        if lightAovName not in self.zsl_zsl.keys():
                            self.zsl_zsl[lightAovName] = 1
            v = [x for x in self.zsl_zsl if x not in light_in_world]
            for o in v:
                self.zsl_zsl.pop(o)
            self.layerDict['__basic'][1] = self.zsl_zsl
            self.refreshLightList_run()

    def refreshLightList_run(self):
        self.ui.zsl_lwt02.clear()
        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            pass
        else:
            myGetAllLight = self.layerDict['__basic'][1].keys()
            self.aov_refreshLightList(myGetAllLight)
            print myGetAllLight, 'qwer'

    def aov_refreshLightList(self, myGetAllLight):
        for x in myGetAllLight:
            if x:
                self.myLightitem = zsl_myCheckedItem(x)
                if x in self.error_create_light:
                    self.myLightitem._myLabel.setStyleSheet('color: rgb(255, 0, 0);')
                self.ui.zsl_lwt02.addItem(self.myLightitem)
                try:
                    if self.layerDict['__basic'][1][x]:
                        self.myLightitem._myCheckedBox.setCheckState(Qt.Checked)
                    else:
                        self.myLightitem._myCheckedBox.setCheckState(Qt.Unchecked)
                except:
                    self.myLightitem._myCheckedBox.setCheckState(Qt.Checked)
                self.myLightitem._myCheckedBox.stateChanged.connect(self.zsl_lightFGrpCheck)
                self.ui.zsl_lwt02.setItemWidget(self.myLightitem, self.myLightitem._itemWid)


    def zsl_lightFGrpCheck(self):
        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            pass
        else:
            aa = self.sender().objectName()
            if self.sender().isChecked():
                self.layerDict['__basic'][1][aa] = 1

            else:
                self.layerDict['__basic'][1][aa] = 0
            print '123', self.layerDict

    def myJudge01(self, arg):
        self.myJudge = []
        allParentList = arg.getAllParents()
        for i in allParentList:
            getVis = pm.getAttr('%s.visibility' % i)
            if getVis == False:

                self.myJudge.append(i)

        return self.myJudge

    def aov_setLightAov(self):
        final_light_aovs = []
        key_group = self.layerDict['__basic'][1].keys()
        for key in key_group:
            if key not in self.error_create_light:
                if self.layerDict['__basic'][1][key]:
                    final_light_aovs.append(key)
        aa = ' '.join(final_light_aovs)
        for x in self.all_create.keys():
            getAov = mtoa.aovs.AOVInterface().getAOVNode(x)
            if self.layerDict['__basic'][0]['all_light_group']:
                pm.setAttr('%s.lightGroupsList' % getAov, ' ')
                pm.setAttr('%s.lightGroups' % getAov, 1)
            else:
                pm.setAttr('%s.lightGroups' % getAov, 0)
                if x in self._aovsWhiteList:
                    pm.setAttr('%s.lightGroupsList' % getAov, aa)

    def refresh_zsl_lwt02(self):

        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            pass
        else:
            selectedList = self.ui.listWidget01.currentItem().text()

            for i in self.layerDict[selectedList]['layerAovs'][2]:
                self.myLightitem = QListWidgetItem(i[0])
                if i[1] == 1:
                    self.myLightitem.setCheckState(Qt.Checked)
                else:
                    self.myLightitem.setCheckState(Qt.Unchecked)
                self.ui.zsl_lwt02.addItem(i[0])

    def delete_aovs(self):

        getAov = mtoa.aovs.AOVInterface().getAOVNodes()
        if getAov:
            for x in getAov:
                aa = pm.getAttr(x + '.name')
                mtoa.aovs.AOVInterface().removeAOV(aa)

    def aov_myCreatAov01(self):
        self.delete_aovs()
        self.all_create = {}

        for i in range(49):
            if i < 16:
                for q in self.layerDict.keys():
                    if q != '__basic':
                        if self.layerDict[q]['layerAovs'][0][i] !=0:
                            if self._ordinaryAov[i] not in self.all_create:
                                self.all_create[self._frequentAov[i]] = i
            else:
                w = i - 16
                for q in self.layerDict.keys():
                    if q != '__basic':
                        if self.layerDict[q]['layerAovs'][1][w] != 0:
                            if self._ordinaryAov[w] not in self.all_create:
                                self.all_create[self._ordinaryAov[w]] = w
        print '11111111', self.all_create, 'ffffffffffffff'
        getAov = self.all_create.keys()
        mtoa.aovs.AOVInterface().removeAOVs(getAov)
        if 'Deep' in self.all_create.keys():
            self.aov_Deep()
        if 'AO' in self.all_create.keys():
            self.aov_AO()
        if 'CN' in self.all_create.keys():
            self.aov_CN()
        for i in self.all_create.keys():
            if i not in ['Deep', 'AO', 'CN']:
                mtoa.aovs.AOVInterface().addAOV(i)
    def aov_myCreatAov02(self, layerName):
        been_create = []
        for i in self.all_create.keys():
            for dic in [self._frequentAov, self._ordinaryAov]:
                if i in dic:
                    num = [self._frequentAov, self._ordinaryAov].index(dic)
                    aa = self.layerDict[layerName]['layerAovs'][num]
                    if i not in ['Deep', 'AO', 'CN']:
                        # print i,'qqqqqq'
                        if i not in been_create:
                            # mtoa.aovs.AOVInterface().addAOV(i)
                            been_create.append(i)
                    mel.eval('hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes")')
                    # print 'aaaa', i, aa
                    # print 'ffff', self.all_create.keys()
                    aovNode = mtoa.aovs.AOVInterface().getAOVNode(i)
                    if aa[self.all_create[i]] == 3:
                        pm.editRenderLayerAdjustment(aovNode + ".enabled", layer = layerName)
                        pm.setAttr('%s.enabled' % aovNode, 1)
                    else:
                        pm.editRenderLayerAdjustment(aovNode + ".enabled", layer = layerName)
                        pm.setAttr('%s.enabled' % aovNode, 0)

    def aov_setAbledAovs(self):
        for abled_k, abled_v in self.getAbledJosn.items():
            aovNode = mtoa.aovs.AOVInterface().getAOVNode(abled_k)
            if aovNode:
                if abled_v == 1:
                    pm.editRenderLayerAdjustment(aovNode + ".enabled")
                    pm.setAttr('%s.enabled' % aovNode, 1)
                else:
                    pm.editRenderLayerAdjustment(aovNode + ".enabled")
                    pm.setAttr('%s.enabled' % aovNode, 0)

    def aov_Deep(self):
        mel.eval('hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes")')
        mtoa.aovs.AOVInterface().addAOV('Deep')
        deepAov = mtoa.aovs.AOVInterface().getAOVNode('Deep')
        deepList = mtoa.utils.createLocator('aiAOVDriver', asLight=0)
        pm.delete(deepList[1])
        pm.setAttr("%s.tiled" % deepList[0], 0)
        pm.setAttr(deepList[0] + '.aiTranslator', 'deepexr')
        pm.connectAttr('%s.message' % (deepList[0]), '%s.outputs[0].driver' % (deepAov),
                        f=True)

    def aov_AO(self):
        mel.eval('hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes")')
        time_num = self.time_num + 1
        AO_aov = mtoa.aovs.AOVInterface().addAOV('AO')

        AO_Shader = pm.createNode('aiAmbientOcclusion', shared=True, n='AO_shader%s' % (str(time_num)))
        AO_Shader.samples.set(4)
        AO_Shader.farClip.set(10)
        getAOV = mtoa.aovs.AOVInterface().getAOVNode(AO_aov)
        pm.connectAttr(AO_Shader + '.outColor', getAOV + '.defaultValue', f=True)

    def aov_CN(self):
        mel.eval('hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes")')
        time_num = self.time_num + 1
        CN_aov = mtoa.aovs.AOVInterface().addAOV('CN')

        ramp_shader = pm.createNode('ramp', shared=True, n='ai_CN_ramp%s' % (str(time_num)))
        ramp_shader.colorEntryList[0].position.set(0.2)
        ramp_shader.colorEntryList[1].position.set(1)
        ramp_shader.colorEntryList[0].color.set(1,1,1)
        ramp_shader.colorEntryList[1].color.set(0,0,0)

        FacingRatio_Shader = pm.createNode('aiFacingRatio', shared=True, n='aiFacingRatio%s' % (str(time_num)))
        FacingRatio_Shader.bias.set(0.7)
        FacingRatio_Shader.gain.set(0.3)
        Flat_Shader = pm.createNode('aiFlat', shared=1, n='CN_aiFlat%s' % (str(time_num)))
        getAOV = mtoa.aovs.AOVInterface().getAOVNode(CN_aov)
        pm.connectAttr(Flat_Shader + '.outColor', getAOV + '.defaultValue', f=1)
        pm.connectAttr(FacingRatio_Shader + '.outValue', ramp_shader + '.vCoord', f=1)
        pm.connectAttr(ramp_shader + '.outColor', Flat_Shader + '.color', f=1)

    #########################################################################################
    #########################################################################################
    ## zsl def ##
    #########################################################################################
    #########################################################################################
    def actionAbout(self):
        self._messageBox_about.show()


    def lwtItemadd(self):

        aa = self.sender().objectName()
        if self.createGrp[aa] == True:
            self.createGrp[aa] = False
        else:
            self.createGrp[aa] = True


    def lwt02Itemadd(self):
        selectedList01 = self.ui.listWidget01.selectedItems()[0]
        selectedList01 = self.ui.listWidget01.row(selectedList01)
        selectedList01 = self.ui.listWidget01.item(selectedList01).text()
        aa = self.sender().objectName()
        for q in self.layerDict[selectedList01].keys():
            if q.split('|')[-1] == aa:
                print self.layerDict[selectedList01][q][1][2]
                if self.layerDict[selectedList01][q][1][1] == True:
                    self.layerDict[selectedList01][q][1][1] = False
                else:
                    self.layerDict[selectedList01][q][1][1] = True
        print self.layerDict
        self.lwt_2()
        # self.checkBox01_04run()

    def lwtItem_1(self):
        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            pass
        else:
            selectedList = self.ui.listWidget01.currentItem().text()
            if selectedList in self._allkey():
                self.refreshListWidget()
            else:

                aa = self.layerDict.keys()[selectedListNum]


                self.layerDict[selectedList] = self.layerDict[aa]
                print self.createGrp, 'qqwq', selectedList, aa
                self.createGrp[selectedList] = self.createGrp[aa]
                self.createGrp.pop(aa)
                self.layerDict.pop(aa)
                print self.layerDict

                self.refreshListWidget()

    def pbn_vis(self):
        aa = self.ui.pushButton.isChecked()
        if aa == False:
            # width = self.ui.tab_24.width()
            width = self.width() - 250
            height = self.height()

        if aa == True:
            width = self.width() + 250
            height = self.height()

        print width, height
        # self.resize(1, height)
        # QTimer.singleShot(50, partial(self.yyy, width, height))
        QTimer.singleShot(1, lambda x=width, y=height: self.yyy(x, y))

    def yyy(self, w, h):
        self.resize(w, h)


    def pbn_addL(self):

        addText = self.ui.lineEdit01.text() # 识别输入
        if addText == '':
            addText = 'layer1'
        allRanderLayer = self.allRanderLayer()
        if addText in allRanderLayer: # 排除重名层
            pass
        else:
            # self.ui.listWidget01.addItem(addText) # 加入显示列图

            self.layerDict[addText] = {'layerAovs':[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
                                                    0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,
                                                    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
                                                    0,0,0,0]]} # 更新层字典

            self.createGrp[addText] = True
            self.refreshListWidget()
            self.ui.lineEdit01.clear()


    def _allkey(self):
        allkey = self.layerDict.keys()
        allkey.remove('__basic')
        return allkey

    def refreshListWidget(self):
        self.ui.listWidget01.clear()
        self.ui.listWidget01add.clear()
        # self._mylistWidget = QListWidget(self)
        # self._mylistWidget.resize(300, 400)
        # aa = 0
        for i in self._allkey():
            # print type(i)
            # i = str(i)
            # print type(i)
            # self.ui.listWidget01.addItem(i)
            self.myItem = QListWidgetItem(self.ui.listWidget01)
            # self.myItem.setSizeHint(QSize(100, 18))
            self.myItem.setText(i)
            self.myItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsDragEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)


            self.myItemAdd = QListWidgetItem(self.ui.listWidget01add)
            # self.myItemAdd.setSizeHint(QSize(100, 18))
            self.q_lstChecked = QCheckBox()
            self.q_lstChecked.setStyleSheet('background-color: rgb(100, 100, 100)')
            # self.q_lstChecked.resize(30,30)
            self.q_lstChecked.setObjectName(i)
            self.q_lstChecked.clicked.connect(self.lwtItemadd)
            if self.createGrp[i] == True:
                self.q_lstChecked.setChecked(1)
            else:
                self.q_lstChecked.setChecked(0)

            self.ui.listWidget01add.setItemWidget(self.myItemAdd, self.q_lstChecked)
            # aa = aa + 1

              # 加入显示列图
        # myTtem = setFlags(self.ui.listWidget01)
        # myTtem.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEditable|Qt.ItemIsDragEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsEnabled)



    # delete
    def pbn_del(self):

        selectedList = self.ui.listWidget01.currentItem().text()
        selectedListNum = self.ui.listWidget01.currentRow()
        # self.ui.listWidget01.takeItem(selectedListNum)
        self.layerDict.pop(selectedList) # 更新层字典
        self.createGrp.pop(selectedList)
        self.refreshListWidget()
        self.lwt_1()

    def lwt_1(self):

        selectedListNum = self.ui.listWidget01.currentRow()
        print selectedListNum
        if selectedListNum == -1:
            self.ui.lineEdit01.clear()
            self.ui.listWidget02.clear()
            self.ui.listWidget02add.clear()
            self.ui.zsl_lwt01.clear()
        else:
            rebackText = self.ui.listWidget01.currentItem().text()
            self.ui.lineEdit01.setText(rebackText)
            self.ui.listWidget02.clear()
            self.ui.listWidget02add.clear()
            self.ui.zsl_lwt01.clear()
            self.checkBox01_04run()


    def checkBox01_04run(self):

        self.checkBox01_04()
        self.refreshListWidget01()
        self.zsl_addItem()
        # self.refresh_zsl_lwt02()
        self.refreshLightList_run()
        self.refresh_basic()

    def refresh_basic(self):
        if self.layerDict['__basic'][0]['all_light_group']:
            self.ui.zsl_cbx03.setCheckState(Qt.Checked)
        else:
            self.ui.zsl_cbx03.setCheckState(Qt.Unchecked)
        if self.layerDict['__basic'][0]['merge_aovs']:
            self.ui.zsl_cbx04.setCheckState(Qt.Checked)
        else:
            self.ui.zsl_cbx04.setCheckState(Qt.Unchecked)





    def checkBox01_04(self):
        self.polyCheck = self.ui.checkBox01.isChecked()
        self.groupCheck = self.ui.checkBox02.isChecked()
        self.lightCheck = self.ui.checkBox03.isChecked()
        self.otherCheck = self.ui.checkBox04.isChecked()




    def lwt_2(self):
        selectedListNum02 = self.ui.listWidget02.currentRow()
        if selectedListNum02 == -1:
            pass
        else:
            self.ui.listWidget03.clear()
            self.ui.listWidget03_value.clear()
            self.ui.listWidget03_num.clear()
            listWidget02List, selectedList02 = self.lwt2Selection()
            allType = []
            selectedList = self.ui.listWidget01.currentItem().text()
            # selectedList02 = self.ui.listWidget02.currentItem().text()
            for i in listWidget02List:
                aa = self.layerDict[selectedList][i][0]
                if aa in allType:
                    pass
                else:
                    allType.append(aa)

            # self.refreshObjAttr()

            if allType[0] == 'mesh' and len(allType) == 1 or allType[0] == 'transform' and len(allType) == 1:

                for w in range(len(self.objAttr)):
                    lwt3Text = self.objAttr[w][0] + '   ' + self.objAttr[w][2]
                    lwt3TextValue = str(self.layerDict[selectedList][selectedList02][1][w])
                    if lwt3TextValue == '':
                        lwt3TextValue = '<None>'
                    self.ui.listWidget03.addItem(lwt3Text)
                    self.ui.listWidget03_value.addItem(lwt3TextValue)
                    self.ui.listWidget03_num.addItem(str(w + 1))
                print self.layerDict[selectedList][selectedList02][1][w]
            else:
                if allType[0] == 'aiStandIn' and len(allType) == 1:
                    for w in range(len(self.ass_objAttr)):
                        lwt3Text = self.ass_objAttr[w][0] + '   ' + self.ass_objAttr[w][2]
                        lwt3TextValue = str(self.layerDict[selectedList][selectedList02][1][w])
                        self.ui.listWidget03.addItem(lwt3Text)
                        self.ui.listWidget03_value.addItem(lwt3TextValue)
                        self.ui.listWidget03_num.addItem(str(w + 1))
                else:
                    self.ui.listWidget03.addItem('error')




    def pbn_true(self):
        selectedListNum02 = self.ui.listWidget02.currentRow()
        print 'www', selectedListNum02
        selectedListNum03 = self.ui.listWidget03.currentRow()
        if selectedListNum02 == -1 and selectedListNum03 == -1:
            pass
        else:
            lwt01List = self.ui.listWidget01.currentItem().text()
            lwt02List, curSel= self.lwt2Selection()
            listWidget03List, selectedListNum = self.lwt3Selection()
            print '111111111111111111', selectedListNum
            for w in selectedListNum:
                if self.objAttr[w][1] ==  'Boolean':
                    for i in lwt02List:
                        self.layerDict[lwt01List][i][1][w] = True
                else:
                    pass
        #self.ui.listWidget03.clear()
        print self.layerDict
        self.lwt_2()

    def pbn_false(self):

        selectedListNum02 = self.ui.listWidget02.currentRow()
        selectedListNum03 = self.ui.listWidget03.currentRow()
        if selectedListNum02 == -1 and selectedListNum03 == -1:
            pass
        else:
            lwt01List = self.ui.listWidget01.currentItem().text()
            lwt02List, curSel = self.lwt2Selection()
            listWidget03List, selectedListNum = self.lwt3Selection()
            for w in selectedListNum:
                if self.objAttr[w][1] ==  'Boolean':
                    for i in lwt02List:
                        self.layerDict[lwt01List][i][1][w] = False
                else:
                    pass
        print self.default
        self.lwt_2()

    def pbn_set(self):

        selectedListNum02 = self.ui.listWidget02.currentRow()
        selectedListNum03 = self.ui.listWidget03.currentRow()
        if selectedListNum02 == -1 and selectedListNum03 == -1:
            pass
        else:
            lwt01List = self.ui.listWidget01.currentItem().text()
            lwt02List, curSel = self.lwt2Selection()
            listWidget03List, selectedListNum = self.lwt3Selection()
            print '1 ', lwt01List, '2 ', lwt02List, '3 ', listWidget03List,'4 ', selectedListNum
            value = self.ui.lineEdit02.text()  # 识别输入
            for eve in lwt02List:
                if self.layerDict[lwt01List][eve][0] == 'aiStandIn':
                    value = int(value)
                    if value == 0 or value == 1:
                        for i in lwt02List:
                            for w in selectedListNum:
                                if value == 0:
                                    aa = False
                                    self.layerDict[lwt01List][i][1][w] = aa
                                if value == 1:
                                    aa = True
                                    self.layerDict[lwt01List][i][1][w] = aa




            for w in selectedListNum:

                if self.objAttr[w][1] == 'Boolean':
                    try:
                        value = int(value)
                        if value == 0 or value == 1:
                            for i in lwt02List:
                                if  value == 0:
                                    aa = False
                                    self.layerDict[lwt01List][i][1][w] = aa
                                if value == 1:
                                    aa = True
                                    self.layerDict[lwt01List][i][1][w] = aa
                    except:
                        print 'error type'

                if self.objAttr[w][1] == 'String':
                    for i in lwt02List:
                        self.layerDict[lwt01List][i][1][w] = value

                if self.objAttr[w][1] == 'Inter':
                    try:
                        value = int(value)
                        if self.objAttr[w][3]:
                            if value >= self.objAttr[w][4] and value <= self.objAttr[w][5]:
                                for i in lwt02List:
                                  self.layerDict[lwt01List][i][1][w] = value
                        else:
                            for i in lwt02List:
                                self.layerDict[lwt01List][i][1][w] = value
                    except:
                        print 'error type'

                if self.objAttr[w][1] == 'Float':
                    try:
                        value = float(value)
                        if self.objAttr[w][3]:
                            if value >= self.objAttr[w][4] and value <= self.objAttr[w][5]:
                                for i in lwt02List:
                                  self.layerDict[lwt01List][i][1][w] = value
                        else:
                            for i in lwt02List:
                                self.layerDict[lwt01List][i][1][w] = value
                    except:
                        print 'error type'

        self.lwt_2()


    def allkey(self):

        allkey = []
        for i in self._allkey():
            for q in self.layerDict[i].keys():
                allkey.append(q)
        return allkey


    def repalce(self):
        lwt02List, curSel = self.lwt2Selection()
        if len(lwt02List) == 1 and len(cmds.ls(sl = 1)) == 1:
            newObj = cmds.ls(sl = 1, l = 1)[0]
            newObjShot = newObj.split('|')[-1]
            oldObj = lwt02List[0]
            newObjType = cmds.listRelatives(newObj, shapes=1, f=1)
            if newObjType == None:
                newObjType = cmds.objectType(newObj)
                if 'ight' in newObjType:
                    newObjType = 'light'
            else:
                newObjType = cmds.objectType(newObjType[0])
                if 'ight' in newObjType:
                    newObjType = 'light'
            if newObjType == 'transform':
                if 'light' in newObj:
                    newObjType = 'light'
            allkey = self.allkey()
            if newObj not in allkey:
                for i in self._allkey():
                    for q in self.layerDict[i].keys():
                        if q == oldObj:
                            if newObjType == self.layerDict[i][q][0]:
                                self._checkHave = checkHave(newObj, self.layerDict[i])
                                bb = self._checkHave.main()
                                if bb == 1:
                                    self.layerDict[i][q][2] = newObjShot
                                    self.layerDict[i][newObj] = self.layerDict[i][oldObj]
                                    self.layerDict[i].pop(oldObj)
        self.refreshListWidget01()


    def refreshListWidget02(self):

        self.ui.lineEdit01.clear()
        self.refreshListWidget()
        self.checkBox01_04run()


    def pbn_im(self): # 导入数据

        self._fileDialog01 = QFileDialog.getOpenFileName(self,r'导入模板','',r'json files(*.json)')
        #print self._fileDialog01
        file = open(self._fileDialog01[0])
        #print file
        jsonFile = file.read()
        self.layerDict = json.loads(jsonFile)
        print self.layerDict
        self.createGrp = {}
        for i in self._allkey():
            self.createGrp[i] = True

        self.refreshListWidget02()

        light_aovs_error = self.new_setLightAov() # 得到aov报错
        self.refreshLightList_run()

        # self._objWorn = objWorn()
        # self._objWorn.show()
        layer_error = self.checkObj()

        if layer_error or light_aovs_error:
            self.dia = objWorn(layer_error, light_aovs_error)
            self.dia.show()

    def checkObj(self): # 检查物体是否在maya中存在
        self.objWornmDict = {}
        for k, v in self.layerDict.items():
            if k == '__basic':
                pass
            else:
                xx = [x for x in v.keys() if not cmds.objExists(x)]
                print xx, 'wyx'
                index = xx.index('layerAovs')
                xx.pop(index)
                if xx:
                    self.objWornmDict[k] = xx

        return self.objWornmDict

    def pbn_ex(self): # 导出数据

        self._fileDialog02 = QFileDialog.getSaveFileName(self,r'导出模板','renderLayer',r'json files(*.json)')
        #print self._fileDialog02
        sysstr = platform.system()
        if sysstr == 'Windows':
            f = open(self._fileDialog02[0], 'w')
        elif sysstr == "Linux":
            f = open(self._fileDialog02[0]+'.json', 'w')
        jsonFile = json.dumps(self.layerDict, indent=4)
        f.write(jsonFile)


        # self._fileDialog02.getSaveFileName.save(jsonFile)

    def pbn_creat(self):
        allRenderLayer = cmds.ls(type='renderLayer')
        self.creatLayerList = self.allRanderLayer()
        self.sameLayer = []
        self.differentLayer = []
        for i in self.creatLayerList:
            if i in allRenderLayer:
                self.sameLayer.append(i)
            else:
                self.differentLayer.append(i)
        if bool(self.sameLayer):
            aa = '    '.join(self.sameLayer)
            self._checkLayer = checkLayer()
            self._checkLayer.QLabel.setText(aa)
            self._checkLayer.show()
            self._checkLayer.cb_1.clicked.connect(self._replace)
            self._checkLayer.cb_2.clicked.connect(self._skip)
            self._checkLayer.cb_3.clicked.connect(self._cancle)
        else:
            self.pbn_creat01()


    def _replace(self):

        cmds.editRenderLayerGlobals(currentRenderLayer='defaultRenderLayer') # 无法删除你当前选择的渲染层
        for i in self.sameLayer:
            cmds.delete(i)
        self.pbn_creat01()
        self._checkLayer.close()


    def _skip(self):
        self.creatLayerList = self.differentLayer
        self.pbn_creat01()
        self._checkLayer.close()

    def _cancle(self):
        self._checkLayer.close()

    def pbn_creat01(self): # 创建，选择打钩的层进行创建
        currentRenderLayer = cmds.editRenderLayerGlobals(q=1, currentRenderLayer=1)
        cmds.editRenderLayerGlobals(currentRenderLayer='defaultRenderLayer')
        self.aov_myCreatAov01()
        for i in self.creatLayerList:
            cmds.createRenderLayer(name = i, number = 1, empty = 1)
            cmds.editRenderLayerGlobals(currentRenderLayer = i)
            self.aov_myCreatAov02(i)
            cmds.editRenderLayerGlobals(currentRenderLayer = currentRenderLayer)
            for q in self.layerDict[i].keys():
                if cmds.objExists(q):
                    if self.layerDict[i][q][0] == 'mesh':
                        for w in range(len(self.objAttr)):
                            aa = cmds.listRelatives(q, s = 1, f = 1)[0]
                            if self.layerDict[i][q][1][w] == self.default[w]:
                                try:
                                    cmds.setAttr(aa + '.' + self.objAttr[w][0], self.default[w])
                                except:
                                    cmds.setAttr(aa + '.' + self.objAttr[w][0], self.default[w],type='string')
                            else:
                                try:
                                    cmds.setAttr(aa + '.' + self.objAttr[w][0], self.layerDict[i][q][1][w])
                                except:
                                    cmds.setAttr(aa + '.' + self.objAttr[w][0], self.layerDict[i][q][1][w], type = 'string')
                                cmds.editRenderLayerAdjustment(aa + '.' + self.objAttr[w][0], layer=i)
                                try:
                                    cmds.setAttr(aa + '.' + self.objAttr[w][0], self.default[w])
                                except:
                                    cmds.setAttr(aa + '.' + self.objAttr[w][0], self.default[w],type='string')

                    if self.layerDict[i][q][0] == 'aiStandIn':
                        for w in range(len(self.ass_objAttr)):
                            aa = cmds.listRelatives(q, s = 1, f = 1)[0]
                            cmds.setAttr(aa + '.' + self.ass_objAttr[w][0], self.layerDict[i][q][1][w])
                            if self.layerDict[i][q][1][w] == self.ass_default[w]:
                                pass
                            else:
                                print 'wyx', aa + '.' + self.ass_objAttr[w][0]
                                cmds.editRenderLayerAdjustment(aa + '.' + self.ass_objAttr[w][0], layer=i)
                                cmds.setAttr(aa + '.' + self.ass_objAttr[w][0], self.ass_default[w])


                    if self.layerDict[i][q][0] == 'transform': # 组
                        aa = cmds.listRelatives(q, ad = 1, f = 1) #
                        ww = []
                        for t in aa:
                            bb = cmds.nodeType(t)
                            # print bb
                            if bb == 'mesh':
                                cc = cmds.listRelatives(t, p = 1, f = 1)[0]
                                ww.append(cc)
                        print '11111111111', ww

                        for v in ww:
                            for w in range(len(self.objAttr)):
                                xx = cmds.listRelatives(v, s = 1, f = 1)[0]
                                if self.layerDict[i][q][1][w] == self.default[w]:
                                    pass
                                else:
                                    eveValue = cmds.getAttr(xx + '.' + self.objAttr[w][0])
                                    try:
                                        cmds.setAttr(xx + '.' + self.objAttr[w][0], self.layerDict[i][q][1][w])
                                    except:
                                        cmds.setAttr(xx + '.' + self.objAttr[w][0], self.layerDict[i][q][1][w],
                                                     type='string')
                                    cmds.editRenderLayerAdjustment(xx + '.' + self.objAttr[w][0], layer=i)

                                    try:
                                        cmds.setAttr(xx + '.' + self.objAttr[w][0], eveValue)
                                    except:
                                        cmds.setAttr(xx + '.' + self.objAttr[w][0], eveValue,
                                                     type='string')

                    cmds.editRenderLayerMembers(i, q)

        cmds.setAttr('defaultRenderLayer.renderable',0) # 关闭默认渲染层
        cmds.editRenderLayerGlobals(currentRenderLayer=currentRenderLayer)

        light_aovs_error = self.new_setLightAov() # 检查lightavos的报错
        self.aov_setLightAov() # light aovs
        self.merge_avos_run() # merge aovs

        print self.layerDict
        layer_error = self.checkObj()
        if layer_error or light_aovs_error:
            self.dia = objWorn(layer_error, light_aovs_error)
            self.dia.show()


    def new_setLightAov(self):
        myGetAllLight = self.layerDict['__basic'][1].keys()
        getAllLight = []
        self.error_create_light = []
        lightType = ['aiSkyDomeLight', 'aiAreaLight', 'spotLight', 'directionalLight', 'pointLight']
        aa = pm.ls(type=lightType)
        for x in aa:
            if len(self.myJudge01(x)) == 0:
                lightAovName = pm.getAttr('%s.aiAov' % x)
                getAllLight.append(lightAovName)
        for i in myGetAllLight:
            if i not in getAllLight:
                self.error_create_light.append(i)
        return self.error_create_light




    def pbn_addO(self): # 添加层物体

        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            pass
        else:
            selectedList = self.ui.listWidget01.currentItem().text()
            selectObj = cmds.ls(sl = 1,l = 1) # 得到所选物体的fullpath name
            layerValue = self.layerDict[selectedList]
            abjList = layerValue.keys() # 加aovs
            index = abjList.index('layerAovs') # 加aovs
            abjList.pop(index) # 加aovs
            for i in selectObj:
                if i in abjList:
                    self._messagebox03.show()
                else:
                    bb = 1
                    eveObjType = cmds.listRelatives(i, shapes=1,f = 1)
                    if eveObjType == None:
                        eveObjType = cmds.objectType(i)
                    else:
                        eveObjType = cmds.objectType(eveObjType[0])

                    if eveObjType == 'mesh': # 添加模型时记录属性参数
                        print 'mesh'
                        self._checkHave = checkHave(i, layerValue) # 实例化类checkHave（）
                        bb = self._checkHave.main()
                        if bb == 1:
                            objValue = []

                            for w in self.objAttr:
                                eveValue = cmds.getAttr(i + '.' + w[0])
                                objValue.append(eveValue)
                        else:
                            self._messagebox03.show()
                    else:
                        if eveObjType == 'transform':
                            print 'transform'
                            if 'light' in i:
                                print 'light'
                                eveObjType = 'light'
                                objValue = 'none'
                            else:
                                self._checkHave = checkHave(i, layerValue) # 实例化类checkHave（）
                                bb = self._checkHave.main()
                                if bb == 1:
                                    objValue = [True, True, True, True, 0, 1, 0, 1.0, 0.0, 0.0, u'']
                                else:
                                    self._messagebox03.show()
                        else:
                            if eveObjType == 'aiStandIn':
                                print 'aiStandIn'
                                self._checkHave = checkHave(i, layerValue) # 实例化类checkHave（）
                                bb = self._checkHave.main()
                                if bb == 1:
                                    objValue = [False, True, True, True]
                                else:
                                    self._messagebox03.show()

                            else:
                                if 'ight' in eveObjType:
                                    eveObjType = 'light'
                                objValue = 'none'
                    if bb == 1:
                        layerValue.keys().append(i)
                        aa = i.split('|')[-1]
                        # i = pm.PyNode(i).fullPath()
                        layerValue[i] = [eveObjType,objValue,aa] # 更新字典
                    else:
                        pass
            self.layerDict[selectedList] = layerValue
            self.refreshListWidget01()


    def refreshListWidget01(self):

        selectedListNum = self.ui.listWidget01.currentRow()
        if selectedListNum == -1:
            self.ui.listWidget02.clear()
            self.ui.listWidget02add.clear()
            self.ui.listWidget03.clear()
            self.ui.listWidget03_value.clear()
            self.ui.listWidget03_num.clear()
            self.ui.zsl_lwt02.clear()

        else:
            self.ui.listWidget02.clear()
            self.ui.listWidget02add.clear()
            self.ui.listWidget03.clear()
            self.ui.listWidget03_value.clear()
            self.ui.listWidget03_num.clear()
            self.ui.zsl_lwt02.clear()
            selectedList = self.ui.listWidget01.currentItem().text()
            layerValue = self.layerDict[selectedList]
            self.checkBox01_04()

            first = []
            second = []
            third = []
            forth = []
            abjList = layerValue.keys() # 加aovs
            print abjList, 'wyx'
            index = abjList.index('layerAovs') # 加aovs
            abjList.pop(index)
            print abjList, 'wyx'
            for w in abjList:
                # eveObjType = cmds.listRelatives(w, shapes = 1)
                aa = layerValue[w][2]
                print aa
                eveObjType = layerValue[w][0]
                print '321', eveObjType
                if self.polyCheck == 1:
                    if eveObjType == 'mesh':
                        print 'poly'
                        first.append([w, 255, 255, 255])
                if self.groupCheck == 1:
                    if eveObjType == 'transform':
                        if 'light' in aa:
                                pass
                        else:
                            print 'group'
                            second.append([w, 141, 217, 141])
                if self.lightCheck == 1:
                    if 'ight' in eveObjType:
                        print 'light'
                        forth.append([w, 255, 229, 178])
                    if eveObjType == 'transform':
                        if 'light' in aa:
                            forth.append([w, 255, 229, 178])
                if self.otherCheck == 1:
                    if eveObjType == 'transform' or eveObjType == 'mesh':
                        pass
                    else:
                        if 'ight' in eveObjType:
                            pass
                        else:
                            if eveObjType == 'aiStandIn':
                                print 'aiStandIn'
                                third.append([w, 178, 217, 255])
                            else:
                                print 'other'
                                forth.append([w, 178, 217, 255])

            nowLayerValue = first + second + third # 分成两部分创建 先创建模型、组和代理，再创建灯光等其他东西
            if isinstance(nowLayerValue, list):

                for q in range(len(nowLayerValue)):
                    cc = nowLayerValue[q][0]
                    bb = cc.split('|')[-1]
                    # self.lwt02Item = QListWidgetItem(self.ui.listWidget02)
                    # self.lwt02Item.setText(bb)
                    # self.lwt02Item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsDragEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)

                    self.ui.listWidget02.addItem(bb)
                    if cmds.objExists(cc):
                        self.ui.listWidget02.item(q).setTextColor(QColor(nowLayerValue[q][1], nowLayerValue[q][2], nowLayerValue[q][3]))
                    else:
                        self.ui.listWidget02.item(q).setTextColor(QColor(255, 0, 0))
                    self.lst02ItemAdd = QListWidgetItem(self.ui.listWidget02add)
                    self.q_lst02Checked = QCheckBox()
                    # self.q_lst02Checked.setTextColor(QColor(nowLayerValue[q][1], nowLayerValue[q][2], nowLayerValue[q][3]))
                    self.q_lst02Checked.setStyleSheet('background-color: rgb(100, 100, 100)')
                    self.q_lst02Checked.setObjectName(bb)
                    self.q_lst02Checked.setText('pvb')

                    # self.q_lst02Checked.setTextColor(QColor(nowLayerValue[q][1], nowLayerValue[q][2], nowLayerValue[q][3]))
                    self.q_lst02Checked.clicked.connect(self.lwt02Itemadd)
                    if layerValue[nowLayerValue[q][0]][1][1] == True:
                        self.q_lst02Checked.setChecked(1)
                    else:
                        self.q_lst02Checked.setChecked(0)
                    # self.ui.listWidget02.item(q).setTextColor(QColor.getRgb())
                    self.ui.listWidget02add.setItemWidget(self.lst02ItemAdd, self.q_lst02Checked)

            if isinstance(forth, list):
                for q in range(len(forth)):
                    if isinstance(nowLayerValue, list): # qq是item的序号
                        qq = q + len(nowLayerValue)
                    else:
                        qq = q
                    cc = forth[q][0]
                    bb = cc.split('|')[-1]
                    self.ui.listWidget02.addItem(bb)
                    if cmds.objExists(cc):
                        self.ui.listWidget02.item(qq).setTextColor(QColor(forth[q][1], forth[q][2], forth[q][3]))
                    else:
                        self.ui.listWidget02.item(qq).setTextColor(QColor(255, 0, 0))
                    self.lst02ItemAdd = QListWidgetItem(self.ui.listWidget02add)



    def pbn_removeO(self):

        #selectedListNum02 = self.ui.listWidget02.currentRow()
        selectedList01 = self.ui.listWidget01.currentItem().text()
        layerValue = self.layerDict[selectedList01]
        lwt02List, curSel= self.lwt2Selection()
        for i in lwt02List:
            self.layerDict[selectedList01].pop(i)
        print self.layerDict
        self.ui.listWidget02.clear()
        self.ui.listWidget02add.clear()
        self.checkBox01_04run()

    def pbn_select(self): # 选择物体显示图例中被选中的物体

        selectedListNum02 = self.ui.listWidget02.currentRow()
        if selectedListNum02 == -1:
            pass
        else:
            listWidget02List, curSel = self.lwt2Selection()
        try:
            cmds.select(listWidget02List)
        except:
            self._messagebox04.show()


    def pbn_removeL(self):

        actualLayer = cmds.ls(type = 'renderLayer')
        # allKey = self.layerDict.keys().remove('__basic')
        for i in self._allkey():
            if self.createGrp[i] == True:
                if i in actualLayer:
                    cmds.delete(i)


    def lwt2Selection(self):

        selectedList02 = self.ui.listWidget02.selectedItems()
        selectedList01 = self.ui.listWidget01.selectedItems()[0]
        selectedList01 = self.ui.listWidget01.row(selectedList01)
        selectedList01 = self.ui.listWidget01.item(selectedList01).text()
        lwt02List = []
        for i in selectedList02:
            aa = self.ui.listWidget02.row(i)
            bb = self.ui.listWidget02.item(aa).text()
            for q in self.layerDict[selectedList01].keys():
                if q.split('|')[-1] == bb:
                    lwt02List.append(q)

        curSel = self.ui.listWidget02.currentItem().text()
        for w in self.layerDict[selectedList01].keys():
            if w.split('|')[-1] == curSel:
                curSel = w

        return lwt02List, curSel


    def lwt3Selection(self):

        selectedList03 = self.ui.listWidget03.selectedItems()
        listWidget03List = []
        selectedListNum = []
        for i in selectedList03:
            aa = self.ui.listWidget03.row(i)
            bb = self.ui.listWidget03.item(aa).text()
            selectedListNum.append(aa)
            listWidget03List.append(bb)
        return listWidget03List, selectedListNum


    def allRanderLayer(self):

        layerList = []
        layerCount = self.ui.listWidget01.count ()
        for i in range(layerCount):
            eveLayer = self.ui.listWidget01.item(i).text()
            if self.createGrp[eveLayer] == True:
                layerList.append(eveLayer)
        print layerList, '11222111'
        return layerList



class messageBox01(QMessageBox):
    def __init__(self):
        super(messageBox01, self).__init__()
        self.setGeometry(850, 400, 500, 500)
        self.setWindowTitle('Error')
        self.setText('having the same name!!')

class messageBox02(QMessageBox):
    def __init__(self):
        super(messageBox02, self).__init__()
        self.setGeometry(850, 400,500,500)
        self.setWindowTitle('Error')
        self.setText('choose a layer')

class messageBox03(QMessageBox):
    def __init__(self):
        super(messageBox03, self).__init__()
        self.setGeometry(850, 400,500,500)
        self.setWindowTitle('Error')
        self.setText('having error object!!')

class messageBox04(QMessageBox):
    def __init__(self):
        super(messageBox04, self).__init__()
        self.setGeometry(850, 400,400,300)
        self.setWindowTitle('Error')
        self.setText('without this object')


class checkHave(object):
    def __init__(self, new_y, new_x):
        self.y = new_y
        self.x = new_x
        # super(checkHave, self).__init__()

    def main(self):
        bb = 0
        aa = cmds.listRelatives(self.y, ad=1, f=1)
        if isinstance(aa, list):
            aa = cmds.listRelatives(self.y, ad=1, f=1)
        else:
            aa = []
        cc = cmds.listRelatives(self.y, ap=1, f=1)
        if isinstance(cc, list):
            cc = cmds.listRelatives(self.y, ap=1, f=1)
        else:
            cc = []
        aa = aa + cc
        for tt in aa:
            if tt in self.x.keys():
                bb = 0
                break
            else:
                bb = 1

        return bb

class objWorn(QDialog):
    def __init__(self, new_y, new_x):
        self.y = new_y
        self.x = new_x
        super(objWorn, self).__init__()

        self.setGeometry(600, 500, 400, 300)
        self.setWindowTitle('These objects were not found')
        self.setLayout(QVBoxLayout())
        self.objWorn = QTextEdit()
        self.layout().addWidget(self.objWorn)
        file = []
        for key in self.y.keys():
            w = ' '.join(self.y[key])
            x = u'渲染层 %s 中 %s 不存在' % (key, w)
            file.append(x)
        final_file = '\n'.join(file)


        bb = ' , '.join(self.x)
        bb = bb + u' 在场景中没有'
        part01 = 'randerLayer:\n' + \
             '%s\n' % (final_file)
        part02 = 'light_aovs:\n' + \
                 '%s\n' % bb
        if self.y and self.x:
            all_part = part01 + part02
        else:
            if self.y:
                all_part = part01
            if self.x:
                all_part = part02
        self.objWorn.setText(all_part)



class checkLayer(QWidget):
    def __init__(self, parent=None):
        super(checkLayer, self).__init__(parent)
        # self.randerLayerTool = randerLayerTool()
        self.QLabel = QLabel("")

        gb = QGroupBox()
        self.cb_1 = QPushButton(u"替换")
        self.cb_2 = QPushButton(u"跳过")
        self.cb_3 = QPushButton(u"取消")

        self.layout_cb = QHBoxLayout()
        self.layout_cb.addWidget(self.cb_1)
        self.layout_cb.addWidget(self.cb_2)
        self.layout_cb.addWidget(self.cb_3)
        gb.setLayout(self.layout_cb)
        gb.setMaximumHeight(50)
        mainLayout = QVBoxLayout()
        # mainLayout.addWidget(self.dropArea)
        mainLayout.addWidget(self.QLabel)
        mainLayout.addWidget(gb)


        self.setLayout(mainLayout)

        self.setWindowTitle(u"下列渲染层已存在!")
        self.setMinimumSize(250, 150)

class messageBox_about(QMessageBox):
    def __init__(self):
        super(messageBox_about, self).__init__()
        self.setGeometry(850, 400,400,300)
        self.setWindowTitle('Welcome')
        self.setText('  If you have any questions or Suggestions\n'
                     'Contact me Please!\n'
                     'Thank you for your support\n'
                     '\n'
                     'Author: Kcite\n'
                     'Tel,WeChat: 17721405208\n'
                     'Email: weedelicious@163.com\n'
                     'QQ: 188967804')

class zsl_my_Wid(QWidget):

    def __init__(self, new_text):
        self.__myLabelext = new_text
        super(zsl_my_Wid, self).__init__()


        self._VHbox = QHBoxLayout()
        self._VHbox.setSpacing(5)
        self._VHbox.setMargin(0)

        self._myLabel = QLabel(self.__myLabelext)
        self._myLabel.setStyleSheet('color:rgb(255,255,255)')
        self._myCheckBox = QCheckBox()
        self._myCheckBox.resize(16, 16)
        self._myCheckBox.setObjectName(self.__myLabelext + "_aov")
        self._myCheckBox.setStyleSheet('background-color: rgb(100, 100, 100)')

        self._VHbox.addWidget(self._myLabel)
        self._VHbox.addStretch(1)
        self._VHbox.addWidget(self._myCheckBox)



        self._abled_checkedbox = QCheckBox()
        self._abled_checkedbox.resize(16, 16)
        self._abled_checkedbox.setObjectName(self.__myLabelext + "_abled")
        self._abled_checkedbox.setStyleSheet('background-color: rgb(100, 100, 100)')

        self._VHbox.addWidget(self._abled_checkedbox)


        self.setLayout(self._VHbox)

        self.setObjectName(self.__myLabelext)

class zsl_myCheckedItem(QListWidgetItem):

    def __init__(self,new_text):
        self._text = new_text
        super(zsl_myCheckedItem, self).__init__()
        self.setSizeHint(QSize(self.sizeHint().width(), 20))
        self._itemWid = QWidget()

        self._myCheckedBox = QCheckBox(self._itemWid)
        self._myCheckedBox.setObjectName(self._text)
        self._myCheckedBox.resize(16, 16)
        self._myCheckedBox.setCheckState(Qt.Checked)
        self._myLabel = QLabel(self._text,self._itemWid)

        self._vhox = QHBoxLayout(self._itemWid)
        self._vhox.setMargin(0)
        self._vhox.addWidget(self._myCheckedBox)
        self._vhox.addWidget(self._myLabel)
        self._vhox.addStretch(1)



def getMayaWindow():
    import maya.OpenMayaUI as OpenMayaUI
    ptr = OpenMayaUI.MQtUtil.mainWindow()
    if ptr is not None:
        return sbk.wrapInstance(long(ptr), QWidget)


def main():

    e = randerLayerTool(getMayaWindow())
    cmds.loadPlugin('mtoa', qt=1)
    #################################################
    # cmds.loadPlugin('mtoa', qt=1)
    # pm.setAttr(pm.PyNode('defaultRenderGlobals').currentRenderer, 'arnold')
    # cmds.workspaceControl('unifiedRenderGlobalsWindow', e=1, vis=1)
    # e.BaseSet()
    #################################################
    e.show()
    #import mtoa.lib


if __name__=='__main__':
    app = QApplication(sys.argv)
    e = randerLayerTool()

    e.show()
    sys.exit(app.exec_())